package cn.cmft.jc.transform.parse.strategy;

import cn.cmft.jc.transform.parse.ChangeDetail;
import net.sf.jsqlparser.statement.alter.AlterExpression;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * desc 处理修改字段名称,字段类型等情况
 */
public class ChangeColumnParser implements AlterExpressionParser {
    @Override
    public List<ChangeDetail> parse(AlterExpression alterExpression) {
        ArrayList<ChangeDetail> columns = new ArrayList<>();
        Optional<List<AlterExpression.ColumnDataType>> colDataTypeListOp = Optional.ofNullable(alterExpression.getColDataTypeList());
        if (!colDataTypeListOp.isPresent()){
            return columns;
        }
        String columnOldName = "";
        Optional<String> oldNameOp = Optional.ofNullable(alterExpression.getColumnOldName());
        if (oldNameOp.isPresent()){
            columnOldName = oldNameOp.get().replace("`","");
        }
        for (AlterExpression.ColumnDataType colDataType : alterExpression.getColDataTypeList()) {
            String colName = colDataType.getColumnName().replace("`","");
            String colType = colDataType.getColDataType().getDataType();
            // 如果修改数据类型时候，该类型有参数（eg: varchar），会有这个对象，如果修改为类似int 类型则没有
            List<String> argumentsStringList = colDataType.getColDataType().getArgumentsStringList();
            Optional<List<String>> argumentsOption = Optional.ofNullable(argumentsStringList);
            if (argumentsOption.isPresent()){
                if (!colDataType.getColDataType().getArgumentsStringList().isEmpty()){
                    colType = colType + "(" + String.join(",", argumentsStringList) + ")";
                }
            }
            if (columnOldName.isEmpty()){
                columnOldName = colName;
            }
            columns.add(new ChangeDetail(columnOldName,colName,colType));
        }
        return columns;
    }
}


